<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch">
      <el-form-item label="文章标题" prop="title">
        <el-input maxlength="20" show-word-limit v-model="queryParams.title" placeholder="请输入文章标题" clearable
          @keyup.enter.native="handleQuery" />
      </el-form-item>
      <el-form-item label="文章分类" prop="categoryId">
        <el-select v-model="queryParams.categoryId">
          <el-option v-for="item in listCategoryData" :key="item.id" :label="item.name" :value="item.id">
          </el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="首页标识" prop="homeStatus">
        <el-select v-model="queryParams.homeStatus">
          <el-option v-for="item in homeStatusList" :key="item.id" :value="item.id" :label="item.name">
          </el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="推荐标识" prop="recommendStatus">
        <el-select v-model="queryParams.recommendStatus">
          <el-option v-for="item in homeStatusList" :key="item.id" :value="item.id" :label="item.name">
          </el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="是否上下架" prop="lineStatus">
        <el-select v-model="queryParams.lineStatus">
          <el-option v-for="item in lineStatusList" :key="item.id" :value="item.id" :label="item.name">
          </el-option>
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button type="primary" icon="el-icon-plus" size="mini" @click="handleAdd"
          v-hasPermi="['business:article:add']">新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="danger" icon="el-icon-delete" size="mini" :disabled="multiple" @click="handleDelete"
          v-hasPermi="['business:article:remove']">删除</el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="articleList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="序号" align="center" type="index" />
      <el-table-column label="分类" align="center" prop="categoryId" min-width="150" :show-overflow-tooltip="true"
        :formatter="formatterCategory" />
      <el-table-column label="文章标题" align="center" prop="title" min-width="150" :show-overflow-tooltip="true" />
      <!-- <el-table-column label="文章简介" align="center" prop="summary" min-width="150" :show-overflow-tooltip="true" /> -->
      <!-- <el-table-column label="封面图片URL" align="center" prop="coverImage" width="100">
        <template slot-scope="scope">
          <image-preview :src="scope.row.coverImage" :width="50" :height="50" />
        </template>
</el-table-column> -->
      <el-table-column label="作者" align="center" prop="author" min-width="100" :show-overflow-tooltip="true" />
      <!-- <el-table-column label="文章内容" align="center" prop="content" /> -->
      <!-- <el-table-column label="视频链接" align="center" prop="videoUrl" /> -->
      <el-table-column label="发布时间" align="center" prop="publishedAt" width="180">
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.publishedAt, '{y}-{m}-{d}') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="状态" align="center" prop="status" min-width="100" :show-overflow-tooltip="true">
        <template v-slot="scope">
          <div v-if="scope.row.status == 0">草稿</div>
          <div v-if="scope.row.status == 1">已发布</div>
        </template>
      </el-table-column>
      <el-table-column label="首页标识" align="center" min-width="100" :show-overflow-tooltip="true">
        <template slot-scope="scope">
          <el-switch v-model="scope.row.homeStatus" active-value="1" inactive-value="0"
            @change="handleStatusChange(scope.row, 'homeStatus')"></el-switch>
        </template>
      </el-table-column>
      <el-table-column label="推荐标识" align="center" min-width="100" :show-overflow-tooltip="true">
        <template slot-scope="scope">
          <el-switch v-model="scope.row.recommendStatus" active-value="1" inactive-value="0"
            @change="handleStatusChange(scope.row, 'recommendStatus')"></el-switch>
        </template>
      </el-table-column>

      <el-table-column label="是否上下架" align="center" min-width="100" :show-overflow-tooltip="true">
        <template slot-scope="scope">
          <el-switch v-model="scope.row.lineStatus" active-value="0" inactive-value="1"
            @change="handlelineStatus(scope.row)"></el-switch>
        </template>
      </el-table-column>
      <el-table-column label="排序" align="center" prop="sortOrder" min-width="100" :show-overflow-tooltip="true" />
      <el-table-column label="备注" align="center" prop="remark" min-width="150" :show-overflow-tooltip="true" />
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width" width="150" fixed="right">
        <template slot-scope="scope">
          <el-button v-if="scope.row.status == 0" size="mini" type="text" @click="handleStatus(scope.row)"
            v-hasPermi="['business:article:status']">发布</el-button>
          <el-button size="mini" type="text" @click="handleDetail(scope.row)"
            v-hasPermi="['business:article:detail']">详情</el-button>
          <el-button size="mini" type="text" @click="handleUpdate(scope.row)"
            v-hasPermi="['business:article:edit']">修改</el-button>
          <el-button size="mini" type="text" @click="handleDelete(scope.row)"
            v-hasPermi="['business:article:remove']">删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination v-show="total > 0" :total="total" :page.sync="queryParams.pageNum" :limit.sync="queryParams.pageSize"
      @pagination="getList" />

    <!-- 添加或修改文章对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="700px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="90px">
        <el-form-item label="文章分类" prop="categoryId">
          <el-select v-model="form.categoryId" :disabled="disabled">
            <el-option v-for="item in listCategoryData" :key="item.id" :label="item.name" :value="item.id">
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="文章标题" prop="title">
          <el-input :disabled="disabled" v-model="form.title" placeholder="请输入文章标题" maxlength="20" show-word-limit />
        </el-form-item>
        <el-form-item label="封面图片" prop="coverImage">
          <image-upload :disabled="disabled" v-model="form.coverImage" />
        </el-form-item>
        <el-form-item label="文章简介" prop="summary">
          <el-input :disabled="disabled" v-model="form.summary" type="textarea" placeholder="请输入内容" rows="3"
            maxlength="100" show-word-limit />
        </el-form-item>
        <el-form-item label="文章内容" prop="content">
          <editor v-model="form.content" :min-height="192" />
        </el-form-item>
        <el-row>
          <el-col :span="12">
            <el-form-item label="作者" prop="author">
              <el-input :disabled="disabled" v-model="form.author" placeholder="请输入作者" maxlength="10" show-word-limit />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="发布时间" prop="publishedAt">
              <el-date-picker :disabled="disabled" clearable v-model="form.publishedAt" type="date"
                value-format="yyyy-MM-dd" placeholder="请选择发布时间">
              </el-date-picker>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="排序" prop="sortOrder">
              <el-input-number :disabled="disabled" v-model="form.sortOrder" :min="1" :max="1000" :controls="false"
                label="请输入排序号，越小越靠前"></el-input-number>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="状态" prop="status">
              <el-radio-group v-model="form.status" :disabled="disabled">
                <el-radio v-for="dict in statusList" :key="dict.id" :label="dict.id">{{ dict.name }}</el-radio>
              </el-radio-group>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="首页标识" prop="homeStatus">
              <el-radio-group v-model="form.homeStatus" :disabled="disabled">
                <el-radio v-for="dict in homeStatusList" :key="dict.id" :label="dict.id">{{ dict.name }}</el-radio>
              </el-radio-group>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="是否推荐" prop="recommendStatus">
              <el-radio-group :disabled="disabled" v-model="form.recommendStatus">
                <el-radio v-for="dict in homeStatusList" :key="dict.id" :label="dict.id">{{ dict.name
                }}</el-radio>
              </el-radio-group>
            </el-form-item>
          </el-col>
        </el-row>
        <el-form-item label="是否上下架" prop="lineStatus">
          <el-radio-group :disabled="disabled" v-model="form.lineStatus">
            <el-radio v-for="dict in lineStatusList" :key="dict.id" :label="dict.id">{{ dict.name
            }}</el-radio>
          </el-radio-group>
        </el-form-item>

        <el-form-item label="视频链接" prop="videoUrl">
          <el-input v-model="form.videoUrl" placeholder="请输入视频链接" :disabled="disabled" />
        </el-form-item>
        <el-form-item label="备注" prop="remark">
          <el-input rows="3" show-word-limit maxlength="100" v-model="form.remark" type="textarea" :disabled="disabled"
            placeholder="请输入内容" />
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer" v-if="!disabled">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { listArticle, getArticle, delArticle, addArticle, updateArticle } from "@/api/article/articleList";
import {
  listCategory
} from "@/api/select";
export default {
  name: "Article",
  data() {
    return {
      homeStatusList: [
        {
          id: '0',
          name: "否",
        },
        {
          id: '1',
          name: "是",
        }
      ],
      lineStatusList: [
        {
          id: '0',
          name: "上架",
        },
        {
          id: '1',
          name: "下架",
        }
      ],
      disabled: false,
      statusList: [
        {
          id: 1,
          name: "发布",
        },
        {
          id: 0,
          name: "草稿",
        }
      ],
      listCategoryData: [],
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 文章表格数据
      articleList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        categoryId: null,
        title: null,
        summary: null,
        coverImage: null,
        author: null,
        content: null,
        videoUrl: null,
        publishedAt: null,
        status: null,
        sortOrder: null,
        homeStatus: null,
        lineStatus: null,
        recommendStatus: null
      },
      // 表单参数
      form: {},
      // 表单校验
      rules: {
        content: [
          { required: true, message: "文章内容不能为空", trigger: "blur" },
        ],
        publishedAt: [
          { required: true, message: "发布时间不能为空", trigger: "blur" },
        ],
        author: [
          { required: true, message: "作者不能为空", trigger: "blur" },
        ],
        sucontentmmary: [
          { required: true, message: "文章内容不能为空", trigger: "blur" },
        ],
        summary: [
          { required: true, message: "文章简介不能为空", trigger: "blur" },
        ],
        sortOrder: [
          { required: true, message: "排序不能为空", trigger: "blur" },
        ],
        coverImage: [
          { required: true, message: "封面图片不能为空", trigger: "blur" }
        ],
        categoryId: [
          { required: true, message: "分类不能为空", trigger: "blur" }
        ],
        title: [
          { required: true, message: "文章标题不能为空", trigger: "blur" }
        ],
      }
    };
  },
  created() {
    this.getList();
    listCategory().then(res => {
      this.listCategoryData = res.rows
    })
  },
  methods: {
    handlelineStatus(row) {
      this.$modal.confirm('确认要修改上下架状态吗？').then(function () {
        return updateArticle({
          id: row.id,
          lineStatus: row.lineStatus
        })
      }).then(() => {
        this.$modal.msgSuccess("修改成功")
      }).catch(function () {
        row.lineStatus = row.lineStatus === "1" ? "0" : "1"

      })
    },
    handleStatusChange(row, status) {
      this.$modal.confirm('确认要修改状态吗？').then(function () {
        return updateArticle({
          id: row.id,
          homeStatus: row.homeStatus,
          recommendStatus: row.recommendStatus,
        })
      }).then(() => {
        this.$modal.msgSuccess("修改成功")
      }).catch(function () {
        if (status == 'homeStatus') {
          row.homeStatus = row.homeStatus === "1" ? "0" : "1"
        } else {
          row.recommendStatus = row.recommendStatus === "1" ? "0" : "1"
        }
      })
    },
    formatterCategory(row, column) {
      let type = ""
      this.listCategoryData.forEach(item => {
        if (item.id == row.categoryId) {
          type = item.name
        }
      })
      return type
    },
    /** 查询文章列表 */
    getList() {
      this.loading = true;
      listArticle(this.queryParams).then(response => {
        this.articleList = response.rows;
        this.total = response.total;
        this.loading = false;
      });
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        id: null,
        categoryId: null,
        title: null,
        summary: null,
        coverImage: null,
        author: null,
        content: null,
        videoUrl: null,
        publishedAt: null,
        status: 1,
        homeStatus: '1',
        recommendStatus: '1',
        lineStatus: '0',
        sortOrder: null,
        remark: null
      };
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.id)
      this.single = selection.length !== 1
      this.multiple = !selection.length
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.disabled = false
      this.open = true;
      this.title = "添加文章";
    },
    // 发布
    handleStatus(row) {
      this.$modal.confirm('是否确认发布此文章？').then(function () {
        return updateArticle({
          id: row.id,
          status: 1
        });
      }).then(() => {
        this.$modal.msgSuccess("发布成功");
        this.getList();
      }).catch(() => { });
    },
    handleDetail(row) {
      this.reset();
      this.disabled = true
      getArticle(row.id).then(response => {
        this.form = response.data;
        this.open = true;
        this.title = "文章详情";
      });
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      this.disabled = false
      const id = row.id || this.ids
      getArticle(id).then(response => {
        this.form = response.data;
        this.open = true;
        this.title = "修改文章";
      });
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          if (this.form.id != null) {
            updateArticle(this.form).then(response => {
              this.$modal.msgSuccess("修改成功");
              this.open = false;
              this.getList();
            });
          } else {
            addArticle(this.form).then(response => {
              this.$modal.msgSuccess("新增成功");
              this.open = false;
              this.getList();
            });
          }
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const ids = row.id || this.ids;
      this.$modal.confirm('是否确认删除文章数据项？').then(function () {
        return delArticle(ids);
      }).then(() => {
        this.getList();
        this.$modal.msgSuccess("删除成功");
      }).catch(() => { });
    },
    /** 导出按钮操作 */
    handleExport() {
      this.download('business/article/export', {
        ...this.queryParams
      }, `article_${new Date().getTime()}.xlsx`)
    }
  }
};
</script>
